package com.dongdongshop.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("login")
public class LoginController {

    @RequestMapping("index")
    public String index1(){
        return "index";
    }
    @RequestMapping("login")
    public String login(String userName, String password, Model model){
        //1.获取subject（用户主体（把操作交给SecurityManager））
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户得数据SecurityManager：安全管理器（关联Realm 去找UserRealm的认证方法）
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            //登陆成功
            subject.login(token);
        }catch (UnknownAccountException e){
            System.out.println("账号错误");
            model.addAttribute("message","账号不存在");
            return "index";//跳页面
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            model.addAttribute("message","密码错误");
            return "index";//页面
        }
        //登录成功跳转
        return "admin/index";
    }
}
